import { app, shell, BrowserWindow, ipcMain, Tray, Menu, globalShortcut} from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import path from 'path'

function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    // x: width - 150,
    // y: height - 300,
    width: 280,
    height: 550,
    show: false,
    maximizable: false,
    minimizable: false,
    resizable: false,
    fullscreenable: false,
    frame: false,
    transparent: true,
    hasShadow: false,
    alwaysOnTop: true,
    titleBarStyle: 'customButtonsOnHover',
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegration: true,
      webSecurity:false // 禁用同源策略
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
    mainWindow.setSkipTaskbar(true)
  })
// 监听渲染线程窗体移动同时改变主进程位置
  ipcMain.on('moveBounds', (event:any, x:any, y:any, width:any, height:any) => {
    if(event.frameId!=mainWindow.webContents.id) return;
    let newBounds = {
      x: parseInt(x),
      y: parseInt(y),
      width: parseInt(width),
      height: parseInt(height),
    }
    mainWindow.setBounds(newBounds)
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    // 跳转指定页面
    // await recordsListWindow.loadURL(process.env['ELECTRON_RENDERER_URL']+`/#/xxxx`);
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
    // await recordsListWindow.loadFile(join(__dirname, '../renderer/index.html'),{hash:'/xxxx'});
  }
  let tray = new Tray(path.join(__dirname, '../../resources/icon.png'));
  const trayMenu = Menu.buildFromTemplate([
    {
      label: 'Show',
      click: () => {
        mainWindow.show();
      }
    },
    {
      label: 'Hide',
      click: () => {
        mainWindow.hide();
      }
    },
    { type: 'separator' },
    {
      label: 'Exit',
      click: () => {
        app.quit();
      }
    }
  ]);
  tray.setContextMenu(trayMenu);
  tray.setToolTip('Electron App');
  globalShortcut.register('Alt+CommandOrControl+F1', () => {
    mainWindow.webContents.send('runAnimation',"1");
  });
  globalShortcut.register('Alt+CommandOrControl+F2', () => {
    mainWindow.webContents.send('runAnimation',"2");
  });
  globalShortcut.register('Alt+CommandOrControl+F3', () => {
    mainWindow.webContents.send('runAnimation',"3");
  });
  globalShortcut.register('Alt+CommandOrControl+F4', () => {
    mainWindow.webContents.send('runAnimation',"4");
  });
  globalShortcut.register('Alt+CommandOrControl+F5', () => {
    mainWindow.webContents.send('runAnimation',"5");
  })

}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {

  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})


// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
